// 全局状态
let isEditing = false;
let currentBookId = null;

// DOM元素
const bookForm = document.getElementById('bookForm');
const submitBtn = document.getElementById('submitBtn');
const cancelEditBtn = document.getElementById('cancelEdit');
const bookListBody = document.getElementById('bookListBody');
const refreshBtn = document.getElementById('refreshBtn');
const loadingIndicator = document.getElementById('loadingIndicator');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadBooks();

    // 表单提交事件
    bookForm.addEventListener('submit', handleFormSubmit);

    // 刷新按钮事件
    refreshBtn.addEventListener('click', loadBooks);

    // 取消编辑事件
    cancelEditBtn.addEventListener('click', cancelEdit);
});

// 加载图书列表
async function loadBooks() {
    showLoading(true);

    try {
        const response = await fetch('/api/book',{
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
        });
        if (!response.ok) throw new Error('获取图书失败');

        const books = await response.json();
        renderBookList(books);
    } catch (error) {
        showToast(error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 渲染图书列表
function renderBookList(books) {
    bookListBody.innerHTML = '';

    if (books.length === 0) {
        bookListBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无图书数据</td></tr>';
        return;
    }

    books.forEach(book => {
        const row = document.createElement('tr');

        row.innerHTML = `
            <td>${book.id}</td>
            <td>${book.name}</td>
            <td>${book.authors.join(', ')}</td>
            <td>${book.press}</td>
            <td class="action-buttons">
                <button class="btn success edit-btn" data-id="${book.id}">编辑</button>
                <button class="btn danger delete-btn" data-id="${book.id}">删除</button>
            </td>
        `;

        bookListBody.appendChild(row);
    });

    // 添加事件监听
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', handleEdit);
    });

    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', handleDelete);
    });
}

// 处理表单提交
async function handleFormSubmit(e) {
    e.preventDefault();

    const bookData = {
        id: document.getElementById('id').value,
        name: document.getElementById('name').value,
        authors: document.getElementById('authors').value.split(',').map(a => a.trim()),
        press: document.getElementById('press').value
    };

    try {
        if (isEditing) {
            await updateBook(bookData);
        } else {
            await addBook(bookData);
        }
        resetForm();
        loadBooks();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

// 添加图书
async function addBook(book) {
    const response = await fetch('/api/book', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(book)
    });

    if (!response.ok) {
        throw new Error('添加图书失败');
    }

    showToast('图书添加成功', 'success');
}

// 更新图书
async function updateBook(book) {
    const response = await fetch(`/api/book/${book.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(book)
    });

    if (!response.ok) {
        throw new Error('更新图书失败');
    }

    showToast('图书更新成功', 'success');
}

// 删除图书
async function handleDelete(e) {
    const bookId = e.target.dataset.id;
    if (!confirm(`确定要删除 ISBN 为 ${bookId} 的图书吗？`)) return;

    try {
        const response = await fetch(`/api/book/${bookId}`, {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' }
        });

        if (!response.ok) throw new Error('删除图书失败');

        showToast('图书删除成功', 'success');
        loadBooks();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

// 编辑图书
async function handleEdit(e) {
    const bookId = e.target.dataset.id;

    try {
        const response = await fetch(`/api/book/${bookId}`,{
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
        });
        if (!response.ok) throw new Error('获取图书信息失败');

        const book = await response.json();
        populateForm(book);

        // 设置编辑状态
        isEditing = true;
        currentBookId = bookId;
        submitBtn.textContent = '更新图书';
        cancelEditBtn.classList.remove('hidden');
        document.getElementById('id').readOnly = true;
    } catch (error) {
        showToast(error.message, 'error');
    }
}

// 填充表单
function populateForm(book) {
    document.getElementById('id').value = book.id;
    document.getElementById('name').value = book.name;
    document.getElementById('authors').value = book.authors.join(', ');
    document.getElementById('press').value = book.press;
}

// 取消编辑
function cancelEdit() {
    resetForm();
}

// 重置表单
function resetForm() {
    bookForm.reset();
    isEditing = false;
    currentBookId = null;
    submitBtn.textContent = '添加图书';
    cancelEditBtn.classList.add('hidden');
    document.getElementById('id').readOnly = false;
}

// 显示/隐藏加载指示器
function showLoading(show) {
    loadingIndicator.style.display = show ? 'block' : 'none';
}

// 显示Toast通知
function showToast(message, type) {
    const toast = document.createElement('div');
    toast.classList.add('toast', type);
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}